package netlog

import (
	"encoding/hex"
	"fmt"
	"os"
	"strings"
	"unicode"

	"github.com/google/gopacket"
	"github.com/google/gopacket/layers"
	"github.com/google/gopacket/pcap"
)

func IsChinese(str string) bool {
	var count int
	for _, v := range str {
		if unicode.Is(unicode.Han, v) {
			count++
			break
		}
	}
	return count > 0
}

// func IsChineseChar(str string) bool {
// 	for _, r := range str {
// 		if unicode.Is(unicode.Scripts["Han"], r) || (regexp.MustCompile("[\u3002\uff1b\uff0c\uff1a\u201c\u201d\uff08\uff09\u3001\uff1f\u300a\u300b]").MatchString(string(r))) {
// 			return true
// 		}
// 	}
// 	return false
// }

func printPacketInfo(packet gopacket.Packet, file *os.File, filter string) {
	ipLayer := packet.Layer(layers.LayerTypeIPv4)
	var src, dst, payload string
	if ipLayer != nil {
		ip, _ := ipLayer.(*layers.IPv4)
		src, dst = ip.SrcIP.String(), ip.DstIP.String()
		// fmt.Printf("[From %s-> to %s]", ip.SrcIP, ip.DstIP)
	}
	// 解析以太网层
	tcpLayer := packet.Layer(layers.LayerTypeTCP)
	if tcpLayer != nil {
		// fmt.Println("TCP layer detected.")
		tcp, _ := tcpLayer.(*layers.TCP)
		// fmt.Printf("From port %d to %d\n", tcp.SrcPort, tcp.DstPort)
		payload = hex.EncodeToString(tcp.Payload)
		// fmt.Println(hex.EncodeToString(tcp.Payload))
	}
	filters := strings.Split(filter, ",")
	if len(payload) > 0 {

		for _, f := range filters {
			if !strings.Contains(payload, f) {
				return
			}
		}

		fmt.Fprintf(file, "[%s -> %s] %s\n", src, dst, payload)

	}
}

func AnalysisNetlog(netlog, outFile, filter string) {
	fmt.Printf("Analysis netlog file1:%s\n", netlog)
	handle, err := pcap.OpenOffline(netlog)
	if err != nil {
		fmt.Printf("Error opening pcap file:%s", netlog)
		return
	}
	defer handle.Close()

	outFileHandle, err := os.Create(outFile)
	if err != nil {
		fmt.Printf("Error creating output file: %s\n", outFile)
		return
	}
	defer outFileHandle.Close()
	fmt.Printf("Analysis netlog file:%s\n", netlog)

	packetSource := gopacket.NewPacketSource(handle, handle.LinkType())
	for packet := range packetSource.Packets() {
		// Do something with a packet here.
		printPacketInfo(packet, outFileHandle, filter)
	}
}
